package com.qf.oa_system.realm;

import com.qf.oa_system.entity.User;
import com.qf.oa_system.service.PermissionsService;
import com.qf.oa_system.service.RolesService;
import com.qf.oa_system.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RolesService rolesService;

    @Autowired
    private PermissionsService permissionsService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String uname = (String) principalCollection.getPrimaryPrincipal();
        Set<String> roles = rolesService.getRoleByUname(uname);
        Set<String> permissions = permissionsService.listPermissions(uname);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(roles);
        simpleAuthorizationInfo.setStringPermissions(permissions);
        System.out.println(roles);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1. token 中获取登录的 username! 注意不需要获取password.
//        UsernamePasswordToken t = (UsernamePasswordToken) token;
        String userName= token.getPrincipal().toString();
        //2. 获取数据库中的密码和盐
        User user =userService.queryByName(userName);
        String passwordInDB = user.getUserPassword();
        String salt = user.getSalt();
        //3. 盐放进去
        //   这样通过spirng-shiro.xml里配置的 HashedCredentialsMatcher 进行自动校验
        //   认证信息里存放账号密码, getName() 是当前Realm的继承方法,通常返回当前类名 :AdminDatabaseRealm
        //   返回实例化
        SimpleAuthenticationInfo a = new SimpleAuthenticationInfo(userName,passwordInDB, ByteSource.Util.bytes(salt),getName());
        return a;
    }
}
